import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods


def news_list(request):
    latest_news = News.objects.filter(type=0).order_by('-create_time')[:5]  # 获取最新的新闻
    latest_activities = News.objects.filter(type=1).order_by('-create_time')[:5]  # 获取最新的活动
    latest_announcements = News.objects.filter(type=2).order_by('-create_time')[:5]  # 获取最新的公告

    context = {
        'latest_news': latest_news,
        'latest_activities': latest_activities,
        'latest_announcements': latest_announcements
    }
    return render(request, 'news.html', context)


def news_manage(request):
    news_list = News.objects.all()
    news_data = [
        {
            'id': news.id,
            'title': news.title,
            'content': news.content,
            'img': news.img,
            'type': news.get_type_display(),  # 获取类型的显示值
            'create_time': news.create_time.strftime('%Y-%m-%d %H:%M:%S')  # 格式化日期时间
        } for news in news_list
    ]
    return JsonResponse({'news': news_data})


from .models import News


@require_http_methods(["POST"])
def update_news(request, news_id):
    try:
        data = json.loads(request.body)
        news = News.objects.get(pk=news_id)
        news.title = data.get('title', news.title)
        news.content = data.get('content', news.content)
        news.img = data.get('img', news.img)
        news.type = data.get('type', news.type)
        news.save()
        return JsonResponse({'message': 'News updated successfully'})
    except News.DoesNotExist:
        return JsonResponse({'error': 'News not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@require_http_methods(["DELETE"])
def delete_news(request, news_id):
    try:
        news = News.objects.get(pk=news_id)
        news.delete()
        return JsonResponse({'message': 'News deleted successfully'})
    except News.DoesNotExist:
        return JsonResponse({'error': 'News not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def create_news(request):
    if request.method == "POST":
        data = json.loads(request.body)
        news = News.objects.create(
            title=data['title'],
            content=data['content'],
            img=data['img'],
            type=data['type']
        )
        return JsonResponse({'message': 'News created successfully', 'id': str(news.id)}, status=201)
    else:
        return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
